package common.sql;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author: Han
 * @date: 2018/6/26 10:11
 * @dscription: 数据库连接池对象
 */
public class DataSource {

    private static BasicDataSource DATA_SOURCE;

    /**
     * 初始化线程池
     */
    private static void initPool() {

        DATA_SOURCE = new BasicDataSource();

        DATA_SOURCE.setDriverClassName("com.mysql.jdbc.Driver");
        DATA_SOURCE.setUrl("jdbc:mysql://192.168.10.209:3306/scmob_system");
        DATA_SOURCE.setUsername("root");
        DATA_SOURCE.setPassword("pass123@209");
        //设置空闲和借用的连接的最大总数量，同时可以激活。
        DATA_SOURCE.setMaxTotal(60);
        //设置初始大小
        DATA_SOURCE.setInitialSize(10);
        //最小空闲连接
        DATA_SOURCE.setMinIdle(5);
        //最大空闲连接
        DATA_SOURCE.setMaxIdle(10);
        //超时等待时间毫秒
        DATA_SOURCE.setMaxWaitMillis(1000 * 20);
        //removeAbandoned  ：不自动回收连接
        DATA_SOURCE.setRemoveAbandonedOnBorrow(false);
        DATA_SOURCE.setRemoveAbandonedOnMaintenance(false);
        //保持持久连接
        DATA_SOURCE.setTestOnBorrow(true);
        DATA_SOURCE.setTestOnReturn(true);
        DATA_SOURCE.setTestWhileIdle(true);
        DATA_SOURCE.setValidationQuery("SELECT 1 FROM DUAL");
        //setRemoveAbandonedOnMaintenance
        DATA_SOURCE.setRemoveAbandonedOnMaintenance(true);
        //记录日志
        DATA_SOURCE.setLogAbandoned(true);
        //设置不自动提交
        DATA_SOURCE.setDefaultAutoCommit(false);
        System.out.println("初始化数据库连接池完成");
    }

    /**
     * 获取连接
     *
     * @return 连接
     */
    static Connection getConnection() throws SQLException {
        if (Objects.isNull(DATA_SOURCE) || DATA_SOURCE.isClosed()) {
            initPool();
        }

        return DATA_SOURCE.getConnection();
    }

    /**
     * 归还连接
     *
     * @param connection 连接
     */
    static void close(Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭线程池
     */
    public static void closePool() {
        try {
            DATA_SOURCE.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
